package com.situ.service.impl;
    
    import cn.hutool.core.util.IdUtil;
    import com.situ.config.MinioProperty;
    import com.situ.context.BaseContext;
    import com.situ.domain.entity.TUser;
    import com.situ.service.FileService;
    import com.situ.service.UserService;
    import io.minio.*;
    import lombok.RequiredArgsConstructor;
    import org.springframework.stereotype.Service;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    @Service
    @RequiredArgsConstructor
    public class FileServiceImpl implements FileService {
    
    
        private final MinioClient minioClient;
    
        private final MinioProperty minioProperty;

        private final UserService userService;
    
        /**
         * 上传文件
         *
         * @param file
         * @return
         */
        @Override
        public String upload(MultipartFile file) {
            try {
                boolean bucketExists = minioClient
                        .bucketExists(
                                BucketExistsArgs
                                        .builder()
                                        .bucket(minioProperty.getBucketName())
                                        .build());
                if (!bucketExists) {
                    // 桶不存在,创建桶
                    minioClient.makeBucket(
                            MakeBucketArgs
                                    .builder()
                                    .bucket(minioProperty.getBucketName())
                                    .build());
                    // 调整桶的权限
                    minioClient.setBucketPolicy(
                            SetBucketPolicyArgs
                                    .builder()
                                    .bucket(minioProperty.getBucketName())
                                    .config(createBucketPolicyConfig(minioProperty.getBucketName()))
                                    .build()
                    );
                }
                // 上传文件
                String filename = new SimpleDateFormat("yyyyMMdd").format(new Date()) +
                        "/" + IdUtil.simpleUUID() + "_" + file.getOriginalFilename();
                minioClient.putObject(
                        PutObjectArgs
                                .builder()
                                .bucket(minioProperty.getBucketName())
                                .object(filename) // 设置文件名
                                .contentType(file.getContentType())
                                .stream(file.getInputStream(), file.getSize(), -1)
                                .build()
                );
                // 拼接文件访问路径
                String url = String.join("/",
                        minioProperty.getEndpoint(),
                        minioProperty.getBucketName(),
                        filename);
                return url;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public String uploadAvata(MultipartFile file) {
            String url = this.upload(file);
            userService.lambdaUpdate()
                    .eq(TUser::getUid, BaseContext.getCurrentId())
                    .set(TUser::getAvatar, url)
                    .set(TUser::getModifiedTime, new Date())
                    .set(TUser::getModifiedUser, BaseContext.getCurrentId().toString())
                    .update();
            return url;
        }

        private String createBucketPolicyConfig(String bucketName) {
    
            return """
                    {
                      "Statement" : [ {
                        "Action" : "s3:GetObject",
                        "Effect" : "Allow",
                        "Principal" : "*",
                        "Resource" : "arn:aws:s3:::%s/*"
                      } ],
                      "Version" : "2012-10-17"
                    }
                    """.formatted(bucketName);
        }
    
    
    }
